<?php

namespace common\models\enroll;

use Yii;
use common\helpers\ArrayHelper;
use Alipay\aop\request\alipay\TradeRequest;
use frontend\modules\trade\models\TradeOrderForm;
use common\helpers\Url;

/**
 * This is the model class for table "{{%enroll}}".
 *
 * @property int $id
 * @property int $user_id 注册用户UID
 * @property int $channel_id 报名类型：0线上，1线下
 * @property int $admin_id
 * @property int $group_id 团队ID
 * @property int $subitem_id 赛段ID
 * @property int $match_id 比赛ID
 * @property int $item_id 报名项目
 * @property string $cost 报名费用
 * @property string $discount 优惠金额
 * @property string $currency
 * @property string $order_no 报名费用订单号
 * @property int $trade_id 报名费用订单ID
 * @property string $out_trade_no 报名费用订单ID
 * @property int $pay_time 费用支付时间
 * @property int $created_at
 * @property int $updated_at
 * @property int $audit_status 审核状态：-1 审核未通过 0 未审核 1 已审核通过
 * @property int $status 报名状态 ：-1 取消，0默认，1已确认，2报名成功
 * @property int $site_id 站点ID
 */
class Enroll extends \common\db\ActiveRecord {

    use \common\traits\Constants;

    const STATUS_COMPLETE = 100; //已完成,待评价
    const STATUS_SUCCESS = 200; //成功订单已关闭
    const STATUS_PAID = 20; //已付款,待发货
    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;
    CONST STATUS_CANCEL = -1;
    CONST STATUS_RETURN = -100;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%enroll}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'channel_id', 'admin_id', 'group_id', 'match_id', 'item_id', 'subitem_id', 'trade_id', 'pay_time', 'created_at', 'updated_at', 'audit_status', 'status', 'site_id'], 'integer'],
            [['cost', 'discount'], 'number'],
            [['order_no', 'out_trade_no'], 'string'],
            [['currency'], 'string', 'max' => 3],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '注册用户UID',
            'channel_id' => '报名类型：0线上，1线下',
            'admin_id' => 'Admin ID',
            'group_id' => '团队ID',
            'match_id' => '比赛ID',
            'subitem_id' => '赛段ID',
            'item_id' => '报名项目',
            'cost' => '报名费用',
            'discount' => '优惠金额',
            'currency' => 'Currency',
            'order_no' => '报名费用订单ID',
            'out_trade_no' => '报名费用订单ID',
            'pay_time' => '报名费用订单ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'audit_status' => '审核状态：-1 审核未通过 0 未审核 1 已审核通过',
            'status' => '报名状态',
            'site_id' => '站点ID',
            //
            'subitem' => '赛段',
        ];
    }

    public function getTrade() {
        return $this->hasOne(\common\models\trade\Trade::className(), ['id' => 'trade_id']);
    }

    public function getAmount() {
        return $this->cost - $this->discount;
    }

    public function getGrade() {
        return $this->hasOne(MarathonEnrollPlayerData::className(), ['data_id' => 'id']);
    }

    public function getSubitem() {
        $items = [
            0 => '全部赛段',
            1 => '凯里赛段',
            2 => '雷山赛段',
            3 => '丹寨赛段',
            4 => '雷山+丹寨赛段',
        ];
        return ArrayHelper::getValue($items, $this->subitem_id);
    }

    public function getSubitemText() {
        if (in_array($this->item_id, [3, 4, 5])) {
            return $this->subitem;
        }
        return '';
    }

    public function isPayment() {
        if (!$this->trade) {
            return false;
        }
        if ($this->trade->isPay()) {
            if ($this->pay_time > $this->created_at && $this->out_trade_no) {
                return true;
            } else {
                $this->pay_time = $this->trade->updated_at;
                $this->out_trade_no = $this->trade->trade_no;
                return $this->save();
            }
        }
        return false;
    }

    public function getConsoleUrl() {
        if ($this->status == static::STATUS_DEFAULT) {
            return ['/enroll/match/improve', 'id' => $this->id];
        }
        return ['/enroll/match/view', 'id' => $this->id];
    }

    public function isSuccess() {
        if ($this->pay_time > $this->created_at && $this->out_trade_no) {
            if ($this->status != static::STATUS_SUCCESS) {
                $this->status = static::STATUS_SUCCESS;
            }
            return true;
        }
        return false;
    }

    public function getMatch() {
        return $this->hasOne(\common\models\match\Match::className(), ['id' => 'match_id']);
    }

    public function getMatchItem() {
        return $this->hasOne(\common\models\match\MatchItem::className(), ['id' => 'item_id']);
    }

    public function getPlayer() {
        return $this->hasOne(MarathonEnrollPlayer::className(), ['enroll_id' => 'id'])->orderBy(['listorder' => SORT_ASC]);
    }

    public function getPlayers() {
        return $this->hasMany(MarathonEnrollPlayer::className(), ['enroll_id' => 'id']);
    }

    public function getStatusText() {
        if ($this->status == static::STATUS_SUCCESS) {
            return '报名成功';
        }
        if ($this->status == static::STATUS_ACTIVE) {
            return '待支付';
        }
        if ($this->status == static::STATUS_DEFAULT) {
            if (count($this->players) > 0) {
                return '待确认';
            }
            return '待填写信息';
        }
        return '';
    }

    public function getStatusIcon() {
        if ($this->status == static::STATUS_SUCCESS) {
            return 'fa fa-sign-language';
        }
        if ($this->status == static::STATUS_ACTIVE) {
            return 'fa fa-clock-o';
        }
        if ($this->status == static::STATUS_DEFAULT) {
            if (count($this->players) > 0) {
                return 'fa fa-share';
            }
            return 'fa fa-pencil-square';
        }
        return 'fa fa-circle-o';
    }

    public function getCostText() {
        $cost = $this->matchItem->cost;
        if ($cost > 0) {
            return '￥' . $cost * count($this->players);
        }
        return '免费';
    }

    public function autoPayment() {
        if ($this->item_id == 5) {
            $this->pay_time = time() + 10;
            $this->out_trade_no = $this->order_no;
            $this->status = static::STATUS_SUCCESS;
        }
    }

    public function generateNo() {
        if ($this->order_no) {
            return $this->order_no;
        }
        $from = $this->match_id;
        $pcode = $this->item_id;
        $date = date('Ymd');
        $rules = [
            'paymode' => $pcode,
            'from' => str_pad(dechex($from), 2, "0", STR_PAD_LEFT),
            'date' => substr($date, 2),
        ];
        do {
            $micro = round((microtime(true) - strtotime($date)) * 10000);
            $rules['micro'] = str_pad($micro, 9, 0, STR_PAD_RIGHT);
            $tn = implode($rules);
            $record = static::find()->where(['order_no' => $tn])->exists();
        } while ($record);
        return $this->order_no = $tn;
    }

    public function getTradeTitle() {
        return $this->matchItem->tradeTitle;
    }

    public function getTradeDescription() {
        return $this->matchItem->tradeBody;
    }

    public function getReturnUrl() {
        return Url::to('@web/enroll/mine', true);
    }

    public function getAlipay() {
        $trade = $this->trade;
        if (!$trade) {
            $model = new TradeOrderForm();
            $model->user_id = Yii::$app->user->id;
            $model->scope = 'enroll';
            $model->paymode = 'alipay';
            $model->order_id = $this->id;
            $trade = $model->save();
        }
        $requestName = TradeRequest::REQUEST_PAGE_PAY;
        $request = new TradeRequest($requestName);
        $request->setNotifyUrl($trade->getNotifyUrl());
        $request->setReturnUrl($this->getReturnUrl());
        $bizContent = [
            'out_trade_no' => $trade->trade_no,
            'product_code' => 'FAST_INSTANT_TRADE_PAY',
            'total_amount' => $trade->amount,
            'subject' => $trade->subject,
            'body' => $trade->body,
            'timeout_express' => '35m',
        ];
        $request->setBizContent($bizContent);
        $alipay = Yii::$app->alipay->transport($trade->partner->account_id);
        $response = $alipay->pageExecute($request);
        return $response;
    }

    public function afterSave($insert, $changedAttributes) {
        $status = ArrayHelper::getValue($changedAttributes, 'status');
        if ($this->status != $status && $this->status == static::STATUS_SUCCESS) {
            $this->noticePlayer();
        }
        parent::afterSave($insert, $changedAttributes);
    }

    public function noticePlayer() {
        $mobile = $this->player->mobile;
        \common\helpers\Utils::sendsms($mobile, "恭喜您，报名成功！您已获得" . $this->match->name . "参赛资格！参赛号码将在报名全部结束后进行公布，敬请留意。");
    }

}
